home *** CD-ROM | disk | FTP | other *** search
- Message-ID: <31098A65.1A40@peoplesoft.com>
- Date: Fri, 26 Jan 1996 18:13:57 -0800
- From: Randal Kuramoto <randal_kuramoto@peoplesoft.com>
- Organization: PeopleSoft
- X-Mailer: Mozilla 2.0b5 (WinNT; I)
- MIME-Version: 1.0
- Newsgroups: comp.lang.c++
- Subject: Limited generalization of templatized classes
- Content-Type: text/plain; charset=us-ascii
- Content-Transfer-Encoding: 7bit
- NNTP-Posting-Host: rkuramo2
- Path: ple-news-01.peoplesoft.com!
-
- Hi,
-
- I ran into (perhaps?) a subtle improvement on a piece of templatized code.
-
- Let's say I have a mixin class such as:
-
- class MixinX
- {
- public:
- virtual ~MixinX() = 0;
-
- Foo();
- };
-
-
- Now, I want to create a templatized class that uses derived classes from
- the Mixin class. I have two versions:
-
- Here is version 1:
-
- template< typename T >
- class ClassY
- {
- public:
- ClassY( T* pT ) : m_pT( pT ) {}; //!!!!!
-
- void Func() { m_pT->Foo(); }; // Calls MixinX::Foo()
-
- private:
- T* m_pT;
- };
-
-
- Here is version 2:
-
- template< typename T >
- class ClassY
- {
- public:
- ClassY( MixinX* pT ) : m_pT( pT ? dynamic_cast< T* >( pT ) : 0 ) {}; //!!!!!
-
- void Func() { m_pT->Foo(); };
-
- private:
- T* m_pT;
- };
-
-
- The difference between the versions is in the ctor parameter type.
-
- In version 1, errors are caught if the linker cannot find a T::Foo().
- If a class Z just happens to have a function with the same signature
- as the MixinX::Foo()...it's possible if Foo is as simple as show here...,
- then ClassY is using a class of objects that may not quite according
- the the behavior specified by the MixinX class.
-
- In version 2, I don't like the downcast, but the compiler catches the
- problem if typename T is not specifically a derived version of MixinX.
- The downcast is done only once in the ctor, and it also helps catch
- misnamed pointers at run-time.
-
- I ran into this when I was looking at Scott Meyer's _More Effective C++_.
- The auto-pointer to a reference-counted object example in his book has
- a template that is similar to version 1 of my example. With the version 2
- tweak, have I made the templatized class better?
-
- Does anyone see any disadvantages or alternatives to version 2?
-
- BTW, the _More Effective C++_ became available on Jan 24 from Addison-Wesley.
- It's a fantastic complement to _Effective C++_.
-
- Randal
-